# -*- coding:utf-8 -*-

from queue import Queue
from threading import Lock, Thread
import time



"""
多线程队列
"""

class myThread(Thread):
    def __init__(self, threadID, name, threadLock, q):
        Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.threadLock = threadLock
        self.q = q

    def run(self):
        print("开启线程：" + self.name)
        process_data(self.name, self.threadLock, self.q)
        print("退出线程：" + self.name)


def process_data(threadName, threadLock, q):
    while not EXIT_FLAG:
        threadLock.acquire()
        if not workQueue.empty():
            data = q.get()
            threadLock.release()
            print("%s: processing %s" % (threadName, data))
        else:
            threadLock.release()
        time.sleep(1)

if __name__ == "__main__":
    EXIT_FLAG = 0
    threadNum = 10
    threadList = []

    for t in range(1, threadNum + 1):
        threadList.append("Thread-" + str(t))

    nameList = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

    threadLock = Lock()
    workQueue = Queue(28)
    threads = []
    threadID = 1

    # 创建新线程
    for tName in threadList:
        thread = myThread(threadID, tName, threadLock, workQueue)
        thread.start()
        threads.append(thread)
        threadID += 1

    # 填充队列
    threadLock.acquire()
    for word in nameList:
        workQueue.put(word)
    threadLock.release()

    # 等待队列清空
    while not workQueue.empty():
        pass

    # 通知线程是时候退出
    EXIT_FLAG = 1

    # 等待所有线程完成
    for t in threads:
        t.join()
    print("退出主线程")
